<!-- templates/index.html -->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>ERP System</title>
    <link rel="stylesheet" href="/static/static/style.css">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <style>
        /* 适配移动端的额外样式 */
        @media (max-width: 900px) {
            .sidebar, .main { min-width: 0 !important; padding: 12px !important; }
            .container { padding: 6px !important; }
            .search-bar { flex-direction: column; gap: 8px; }
        }

        /* 邮箱配置模态框：限制高度并允许滚动 */
        #emailConfigModal .modal-content {
            max-height: 80vh;
            overflow-y: auto;
        }
        /* 小屏下模态宽度适配 */
        @media (max-width: 900px) {
            #emailConfigModal .modal-content {
                width: 92vw !important;
            }
        }
    </style>
</head>
<body>
<div class="container">
    <div class="sidebar">
        <h2 id="warehouse-title" style="cursor: pointer;" ondblclick="editTitle('warehouse-title', '库房')">库房</h2>
        <div class="warehouse-actions">
            <button onclick="showModal()">添加库房</button>
            <button onclick="deleteSelectedWarehouses()" class="delete-btn">删除选中</button>
        </div>
        <ul id="warehouse-list">
            <!-- 库房列表（可拖拽） -->
        </ul>
        <div id="edit-warehouse-modal" class="modal">
            <div class="modal-content">
                <span class="close" onclick="closeEditModal()">&times;</span>
                <h2>编辑库房</h2>
                <label for="edit-warehouse-name">库房名称:</label>
                <input type="text" id="edit-warehouse-name" required>
<!--                <input type="text" id="edit-warehouse-id" required>-->
                <button type="button" id="save-warehouse-edit">保存</button>
                <button type="button" onclick="closeEditModal()">取消</button>
            </div>
        </div>
    </div>
    <div class="main">
        <h2 id="product-title" style="cursor: pointer;" ondblclick="editTitle('product-title', '物资')">物资</h2>
        <div class="search-bar">
            <input type="text" id="product-name-search" placeholder="搜索名称...">
            <input type="text" id="product-model-search" placeholder="搜索型号...">
            <input type="text" id="product-specification-search" placeholder="搜索位置...">
            <button onclick="searchProducts()">搜索</button>
            <button onclick="AllsearchProducts()">搜索全部物资</button>
        </div>
        <div class="action-buttons">
            <button onclick="openAddProductModal()">添加物资</button>
            <button onclick="importProducts()">批量导入</button>
<!--            <button onclick="importProducts()">批量导出</button>-->
            <button onclick="deleteSelectedProducts()" class="delete-btn">删除选中</button>
<!--            <button onclick="editSelectedProducts()" class="edit-btn">编辑选中</button>-->
            <button onclick="showSelectedProducts()">查看选中物资</button>
            <button onclick="openPasswordModal()" style="background: #6c757d; color: white;">密码设置</button>
            <!-- <button onclick="openEmailConfigModal()" style="background: #007bff; color: white;">📧 配置邮箱</button> -->
            <!-- <button onclick="openEmailTestModal()" style="background: #28a745; color: white;">📧 测试邮件</button> -->
        </div>

<!--        <input type="file" id="productFile" />-->
        <span id="selectedWarehouse" style="display: none"></span>
        <span id="isAll" style="display: none"></span>
        <div id="product-list">
            <!-- 物资列表 -->
        </div>
            <!--    分页    -->
        <div id="pagination" style="display: flex; align-items: center; margin: 20px 0; padding: 10px; background-color: #f5f5f5; border-radius: 4px;">
    <span style="margin-right: 10px;">共 <span id="totalCount">0</span> 条</span>
    <select id="pageSizeSelect" style="margin-right: 20px; padding: 5px 10px; border: 1px solid #ccc; border-radius: 4px;">
        <option value="5">5条/页</option>
        <option value="10">10条/页</option>
        <option value="50">50条/页</option>
        <option value="100">100条/页</option>
        <option value="0">显示全部</option>
    </select>
    <button id="prevPage" style="padding: 5px 10px; border: 1px solid #ccc; border-radius: 4px; margin-right: 5px;">上一页</button>
    <span id="currentPage" style="margin: 0 10px;">1</span>
    <button id="nextPage" style="padding: 5px 10px; border: 1px solid #ccc; border-radius: 4px; margin-left: 5px;">下一页</button>
</div>
    </div>


    <!-- 添加库房的模态框 -->
    <div id="add-warehouse-modal" class="modal">
        <div class="modal-content">
            <span class="close">&times;</span>
            <h2 style="padding-left: 200px">添加库房</h2>
            <form id="add-warehouse-form">
                <label for="warehouse-name">库房名称:</label>
                <input type="text" id="warehouse-name" name="name" required>
                 </br>
<!--                <label style="margin-top: 100px" for="warehouse-sort">排序:</label>-->
                <input type="text" id="warehouse-sort" name="sort" style="display: none" required>
                </br>
                <div class="modal-button">
                    <button type="button" onclick="submitAddWarehouse()">提交</button>
                    <button type="button" onclick="closeModal()">取消</button>
                </div>

            </form>
        </div>
    </div>

</div>
<script src="/static/static/script.js"></script>

<!-- 添加选中物资的模态框 -->
<div id="selected-products-modal" class="modal">
    <div class="modal-content" style="width: 1100px">
        <span class="close" onclick="closeSelectedProductsModal()">&times;</span>
        <h2>选中的物资</h2>
        <button onclick="closeSelectedProductsModal()">关闭</button>
        <button onclick="exportProducts()">导出</button>
        <button onclick="batchOutStorage(true)">出库</button>
        <button onclick="batchOutStorage(false)">入库</button>
        <button onclick="DeleteProcessOutbound()" >删除</button>
        <div id="selected-products-list" style="width: 200px"></div>
    </div>
</div>

<!-- 添加物资模态框 -->
<div id="addProductModal" class="modal">
    <div class="modal-content">
        <span class="close" onclick="closeAddProductModal()">&times;</span>
        <h2>添加物资</h2>
        <form id="addProductForm">
            <div class="form-group">
                <label for="productName">物资名称:</label>
                <input type="text" id="productName" name="name" required>
            </div>
            <div class="form-group">
                <label for="productModel">型号:</label>
                <input type="text" id="productModel" name="model" >
            </div>
            <div class="form-group">
                <label for="productSpecification">规格:</label>
                <input type="text" id="productSpecification" name="spec" >
            </div>
            <div class="form-group">
                <label for="location">位置:</label>
                <input type="text" id="location" name="location" required>
            </div>
<!--            <div class="form-group">-->
<!--                <label for="quantity">数量:</label>-->
<!--                <input type="number" id="quantity" name="quantity" required>-->
<!--            </div>-->
            <div class="form-group">
                <label for="in_storage">入库数量:</label>
                <input type="number" id="in_storage" name="in_storage" required>
            </div>
            <div class="form-group">
                <label for="out_storage">入库原因:</label>
                <input type="text" id="out_storage" name="out_storage" required>
            </div>
            <div class="form-group">
                <label for="user_admin">管理员:</label>
                <input type="text" id="user_admin" name="user_admin" required>
            </div>
            <div class="form-group">
                <label for="pic">图片:</label>
                <input type="file" id="pic" name="pic" accept="image/*">
            </div>
            <div class="form-group">
                <label for="remark">备注:</label>
                <input type="text" id="remark" name="remark">
            </div>
            <div class="form-group">
                <label for="email">邮件地址:</label>
                <input type="email" id="email" name="email" placeholder="请输入邮件地址（用于接收提醒）">
            </div>
            <div class="form-actions">
                <button type="submit">添加</button>
                <button type="button" onclick="closeAddProductModal()">取消</button>
            </div>
        </form>
    </div>
</div>

<!-- 密码设置模态框 -->
<div id="passwordModal" class="modal">
    <div class="modal-content" style="max-width: 500px;">
        <span class="close" onclick="closePasswordModal()">&times;</span>
        <h2>密码设置</h2>
        <div id="passwordForm">
            <div class="form-group">
                <label for="currentPassword">当前密码:</label>
                <input type="password" id="currentPassword" placeholder="请输入当前密码">
            </div>
            <div class="form-group">
                <label for="newPassword">新密码:</label>
                <input type="password" id="newPassword" placeholder="请输入新密码">
            </div>
            <div class="form-group">
                <label for="confirmPassword">确认新密码:</label>
                <input type="password" id="confirmPassword" placeholder="请再次输入新密码">
            </div>
            <div class="form-actions">
                <button type="button" onclick="changePassword()">修改密码</button>
                <button type="button" onclick="closePasswordModal()">取消</button>
            </div>
        </div>
        <div id="initialPasswordForm" style="display: none;">
            <div class="form-group">
                <label for="initialPassword">设置初始密码:</label>
                <input type="password" id="initialPassword" placeholder="请输入初始密码">
            </div>
            <div class="form-group">
                <label for="confirmInitialPassword">确认密码:</label>
                <input type="password" id="confirmInitialPassword" placeholder="请再次输入密码">
            </div>
            <div class="form-actions">
                <button type="button" onclick="setInitialPassword()">设置密码</button>
                <button type="button" onclick="closePasswordModal()">取消</button>
            </div>
        </div>
    </div>
</div>

<!-- 邮件测试模态框 -->
<div id="emailTestModal" class="modal" style="display: none;">
    <div class="modal-content">
        <span class="close" onclick="closeEmailTestModal()">&times;</span>
        <h2>📧 测试邮件发送</h2>
        <div class="form-group">
            <label for="testEmailAddress">收件人邮箱:</label>
            <input type="email" id="testEmailAddress" placeholder="请输入要测试的邮箱地址" required>
        </div>
        <div class="form-actions">
            <button type="button" onclick="sendTestEmail()" style="background: #28a745; color: white;">发送测试邮件</button>
            <button type="button" onclick="closeEmailTestModal()">取消</button>
        </div>
        <div id="emailTestResult" style="margin-top: 15px; padding: 10px; border-radius: 4px; display: none;"></div>
    </div>
</div>

<!-- 邮件配置模态框 -->
<div id="emailConfigModal" class="modal" style="display: none;">
    <div class="modal-content" style="max-width: 600px;">
        <span class="close" onclick="closeEmailConfigModal()">&times;</span>
        <h2>📧 配置邮箱（SMTP）</h2>
        <div class="form-group">
            <label for="smtp_host">SMTP 主机:</label>
            <input type="text" id="smtp_host" placeholder="如 smtp.163.com">
        </div>
        <div class="form-group">
            <label for="smtp_port">SMTP 端口:</label>
            <input type="text" id="smtp_port" placeholder="465 或 587">
        </div>
        <div class="form-group">
            <label for="smtp_username">SMTP 用户名:</label>
            <input type="text" id="smtp_username" placeholder="发件人完整邮箱">
        </div>
        <div class="form-group">
            <label for="smtp_password">SMTP 授权码:</label>
            <input type="password" id="smtp_password" placeholder="邮箱授权码（非登录密码）">
        </div>
        <div class="form-group">
            <label for="from_email">发件邮箱:</label>
            <input type="email" id="from_email" placeholder="与用户名保持一致为佳">
        </div>
        <div class="form-group">
            <label for="from_name">发件显示名:</label>
            <input type="text" id="from_name" placeholder="如 ERP系统">
        </div>
        <hr>
        <div class="form-group">
            <label for="config_test_to">测试收件邮箱（可选）:</label>
            <input type="email" id="config_test_to" placeholder="填写则保存后立即发送测试">
        </div>
        <div class="form-actions">
            <button type="button" onclick="saveEmailConfig()" style="background: #007bff; color: white;">保存配置</button>
            <button type="button" onclick="saveConfigAndSendTest()" style="background: #28a745; color: white;">保存并发送测试</button>
            <button type="button" onclick="closeEmailConfigModal()">取消</button>
        </div>
        <div id="emailConfigResult" style="margin-top: 15px; padding: 10px; border-radius: 4px; display: none;"></div>
    </div>
    
</div>

<script>
// 密码管理相关功能
let hasPassword = false;

// 页面加载时检查是否已设置密码
document.addEventListener('DOMContentLoaded', function() {
    checkPasswordExists();
});

// 检查密码是否存在
async function checkPasswordExists() {
    try {
        const response = await fetch('/api/password/check');
        const data = await response.json();
        hasPassword = data.exists;
    } catch (error) {
        console.error('检查密码状态失败:', error);
    }
}

// 打开密码设置模态框
function openPasswordModal() {
    const modal = document.getElementById('passwordModal');
    const passwordForm = document.getElementById('passwordForm');
    const initialPasswordForm = document.getElementById('initialPasswordForm');
    
    if (hasPassword) {
        passwordForm.style.display = 'block';
        initialPasswordForm.style.display = 'none';
    } else {
        passwordForm.style.display = 'none';
        initialPasswordForm.style.display = 'block';
    }
    
    modal.style.display = 'block';
}

// 关闭密码设置模态框
function closePasswordModal() {
    const modal = document.getElementById('passwordModal');
    modal.style.display = 'none';
    
    // 清空表单
    document.getElementById('currentPassword').value = '';
    document.getElementById('newPassword').value = '';
    document.getElementById('confirmPassword').value = '';
    document.getElementById('initialPassword').value = '';
    document.getElementById('confirmInitialPassword').value = '';
}

// 设置初始密码
async function setInitialPassword() {
    const password = document.getElementById('initialPassword').value;
    const confirmPassword = document.getElementById('confirmInitialPassword').value;
    
    if (!password) {
        alert('请输入密码');
        return;
    }
    
    if (password !== confirmPassword) {
        alert('两次输入的密码不一致');
        return;
    }
    
    if (password.length < 6) {
        alert('密码长度至少6位');
        return;
    }
    
    try {
        const response = await fetch('/api/password/set', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                password: password
            })
        });
        
        const data = await response.json();
        
        if (response.ok) {
            alert('密码设置成功');
            hasPassword = true;
            closePasswordModal();
        } else {
            alert('密码设置失败: ' + (data.error || '未知错误'));
        }
    } catch (error) {
        alert('密码设置失败: ' + error.message);
    }
}

// 修改密码
async function changePassword() {
    const currentPassword = document.getElementById('currentPassword').value;
    const newPassword = document.getElementById('newPassword').value;
    const confirmPassword = document.getElementById('confirmPassword').value;
    
    if (!currentPassword) {
        alert('请输入当前密码');
        return;
    }
    
    if (!newPassword) {
        alert('请输入新密码');
        return;
    }
    
    if (newPassword !== confirmPassword) {
        alert('两次输入的新密码不一致');
        return;
    }
    
    if (newPassword.length < 6) {
        alert('新密码长度至少6位');
        return;
    }
    
    try {
        const response = await fetch('/api/password/change', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                currentPassword: currentPassword,
                newPassword: newPassword
            })
        });
        
        const data = await response.json();
        
        if (response.ok) {
            alert('密码修改成功');
            closePasswordModal();
        } else {
            alert('密码修改失败: ' + (data.error || '未知错误'));
        }
    } catch (error) {
        alert('密码修改失败: ' + error.message);
    }
}

// 验证密码（供其他页面调用）
async function verifyPassword(password) {
    try {
        const response = await fetch('/api/password/verify', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                password: password
            })
        });
        
        const data = await response.json();
        return data.valid;
    } catch (error) {
        console.error('密码验证失败:', error);
        return false;
    }
}

// 邮件测试相关功能

// 打开邮件测试模态框
function openEmailTestModal() {
    const modal = document.getElementById('emailTestModal');
    const resultDiv = document.getElementById('emailTestResult');
    
    // 清空之前的结果
    resultDiv.style.display = 'none';
    resultDiv.innerHTML = '';
    document.getElementById('testEmailAddress').value = '';
    
    modal.style.display = 'block';
}

// 关闭邮件测试模态框
function closeEmailTestModal() {
    const modal = document.getElementById('emailTestModal');
    modal.style.display = 'none';
}

// 发送测试邮件
async function sendTestEmail() {
    const emailAddress = document.getElementById('testEmailAddress').value.trim();
    const resultDiv = document.getElementById('emailTestResult');
    
    if (!emailAddress) {
        showEmailTestResult('请输入邮箱地址', 'error');
        return;
    }
    
    // 验证邮箱格式
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    if (!emailRegex.test(emailAddress)) {
        showEmailTestResult('请输入有效的邮箱地址', 'error');
        return;
    }
    
    try {
        showEmailTestResult('正在发送测试邮件...', 'info');
        
        const response = await fetch('/api/email/test', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                to_email: emailAddress
            })
        });
        
        const data = await response.json();
        
        if (response.ok) {
            showEmailTestResult('✅ 测试邮件发送成功！请检查收件箱。', 'success');
        } else {
            showEmailTestResult('❌ 邮件发送失败: ' + (data.error || '未知错误'), 'error');
        }
    } catch (error) {
        console.error('发送测试邮件失败:', error);
        showEmailTestResult('❌ 网络错误，请检查网络连接', 'error');
    }
}

// 显示邮件测试结果
function showEmailTestResult(message, type) {
    const resultDiv = document.getElementById('emailTestResult');
    resultDiv.style.display = 'block';
    
    // 根据类型设置样式
    switch (type) {
        case 'success':
            resultDiv.style.backgroundColor = '#d4edda';
            resultDiv.style.color = '#155724';
            resultDiv.style.border = '1px solid #c3e6cb';
            break;
        case 'error':
            resultDiv.style.backgroundColor = '#f8d7da';
            resultDiv.style.color = '#721c24';
            resultDiv.style.border = '1px solid #f5c6cb';
            break;
        case 'info':
            resultDiv.style.backgroundColor = '#d1ecf1';
            resultDiv.style.color = '#0c5460';
            resultDiv.style.border = '1px solid #bee5eb';
            break;
    }
    
    resultDiv.innerHTML = message;
}

// 邮箱配置：打开/关闭模态框
function openEmailConfigModal() {
    const modal = document.getElementById('emailConfigModal');
    const resultDiv = document.getElementById('emailConfigResult');
    resultDiv.style.display = 'none';
    resultDiv.innerHTML = '';
    // 预填现有配置
    preloadEmailConfig();
    modal.style.display = 'block';
}

function closeEmailConfigModal() {
    const modal = document.getElementById('emailConfigModal');
    modal.style.display = 'none';
}

// 预加载现有配置
async function preloadEmailConfig() {
    try {
        const resp = await fetch('/api/email/config');
        const cfg = await resp.json();
        document.getElementById('smtp_host').value = cfg.email_smtp_host || '';
        document.getElementById('smtp_port').value = cfg.email_smtp_port || '';
        document.getElementById('smtp_username').value = cfg.email_smtp_username || '';
        document.getElementById('from_email').value = cfg.email_from_email || '';
        document.getElementById('from_name').value = cfg.email_from_name || '';
        // 授权码不回显
        document.getElementById('smtp_password').value = '';
    } catch (e) {
        console.error('加载邮箱配置失败', e);
    }
}

// 保存配置（仅保存，不发送）
async function saveEmailConfig() {
    const resultDiv = document.getElementById('emailConfigResult');
    try {
        const body = collectEmailConfigBody();
        const resp = await fetch('/api/email/config', {
            method: 'PUT',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify(body)
        });
        const data = await resp.json();
        showEmailConfigResult(resp.ok ? '✅ 配置保存成功' : ('❌ 配置保存失败: ' + (data.error || '未知错误')), resp.ok ? 'success' : 'error');
    } catch (e) {
        showEmailConfigResult('❌ 网络错误: ' + e.message, 'error');
    }
}

// 保存并发送测试（调用 POST /api/email/test，带上 to_email 与配置）
async function saveConfigAndSendTest() {
    const resultDiv = document.getElementById('emailConfigResult');
    const to = (document.getElementById('config_test_to').value || '').trim();
    if (!to) {
        showEmailConfigResult('请填写测试收件邮箱，或使用“保存配置”按钮仅保存。', 'info');
        return;
    }
    // 简单邮箱格式校验
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    if (!emailRegex.test(to)) {
        showEmailConfigResult('请输入有效的测试收件邮箱', 'error');
        return;
    }

    try {
        const body = collectEmailConfigBody();
        body.to_email = to;
        const resp = await fetch('/api/email/test', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify(body)
        });
        const data = await resp.json();
        showEmailConfigResult(resp.ok ? '✅ 已保存并发送测试邮件，请查收。' : ('❌ 发送失败: ' + (data.error || '未知错误')), resp.ok ? 'success' : 'error');
    } catch (e) {
        showEmailConfigResult('❌ 网络错误: ' + e.message, 'error');
    }
}

function collectEmailConfigBody() {
    return {
        smtp_host: document.getElementById('smtp_host').value.trim(),
        smtp_port: document.getElementById('smtp_port').value.trim(),
        smtp_username: document.getElementById('smtp_username').value.trim(),
        smtp_password: document.getElementById('smtp_password').value.trim(),
        from_email: document.getElementById('from_email').value.trim(),
        from_name: document.getElementById('from_name').value.trim()
    };
}

function showEmailConfigResult(message, type) {
    const resultDiv = document.getElementById('emailConfigResult');
    resultDiv.style.display = 'block';
    switch (type) {
        case 'success':
            resultDiv.style.backgroundColor = '#d4edda';
            resultDiv.style.color = '#155724';
            resultDiv.style.border = '1px solid #c3e6cb';
            break;
        case 'error':
            resultDiv.style.backgroundColor = '#f8d7da';
            resultDiv.style.color = '#721c24';
            resultDiv.style.border = '1px solid #f5c6cb';
            break;
        case 'info':
        default:
            resultDiv.style.backgroundColor = '#d1ecf1';
            resultDiv.style.color = '#0c5460';
            resultDiv.style.border = '1px solid #bee5eb';
            break;
    }
    resultDiv.innerHTML = message;
}
</script>

</body>
</html>

